/**
 * 用户管理
 *
 * Created by kongqiang
 * Date 17/4/6
 */
var scripts = [null,
    ctx + '/resource/plugins/ace/components/jqGrid/js/jquery.jqGrid.js',
    ctx + '/resource/plugins/ace/components/jqGrid/js/i18n/grid.locale-cn.js',
    ctx + '/resource/plugins/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js',
    ctx + '/resource/plugins/ace/components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.zh-CN.min.js',
    ctx + '/resource/plugins/bootstrapvalidator/js/bootstrapValidator.min.js',
    ctx + '/resource/plugins/bootstrapvalidator/js/language/zh_CN.js',
    ctx + '/resource/plugins/jquery.jqGrid.patch.src.js',
    ctx + '/resource/plugins/ace/components/_mod/fuelux/tree.js',
    ctx + '/resource/plugins/ace/assets/js/src/elements.treeview.js',
    ctx + '/resource/plugins/ace/components/fuelux/js/wizard.js',
    // ctx + '/resource/plugins/ace/components/jquery-validation/dist/jquery.validate.js',
    // ctx + '/resource/plugins/ace/components/jquery-validation/dist/additional-methods.js',
    // ctx + '/resource/plugins/ace/components/jquery-validation/src/localization/messages_zh.js',
    ctx + '/resource/utils/deptTreeData.js',
    ctx + '/resource/utils/roleTreeData.js',
    null];
pageContentArea.ace_ajax('loadScripts', scripts, function () {
    jQuery(function ($) {
        // treeview
        $('#deptTreeview').ace_tree({
            //dataSource: sampleData['dataSource2'],
            dataSource: remoteDeptDateSource,
            loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
            'open-icon': 'ace-icon fa fa-chevron-down',
            'close-icon': 'ace-icon fa fa-chevron-right',
            'itemSelect': true,
            'folderSelect': true,
            'multiSelect': false,
            'selected-icon': null,
            'unselected-icon': null,
            'folder-open-icon': 'ace-icon tree-plus',
            'folder-close-icon': 'ace-icon tree-minus',
            'cacheItems': false
        }).on('selected.fu.tree', function (event, data) {
            reloadJqGrid('json');
        }).on('deselected.fu.tree', function (event, data) {
            reloadJqGrid('json');
        }).on('closed.fu.tree', function (event, data) {
            reloadJqGrid('json');
        });

        // 默认展开根节点
        $('#deptTreeview').tree('openFolder', $('#deptTreeview').find('.tree-branch')[1]);

        // 初始化功能角色树
        $('#addRoleTab').ace_tree({
            dataSource: remoteRoleDateSource,
            loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
            'open-icon': 'ace-icon fa fa-chevron-down',
            'close-icon': 'ace-icon fa fa-chevron-right',
            'itemSelect': true,
            'folderSelect': true,
            'multiSelect': true,
            'selected-icon': null,
            'unselected-icon': null,
            'folder-open-icon': 'ace-icon tree-plus',
            'folder-close-icon': 'ace-icon tree-minus',
            'cacheItems': false
        });

        // 默认展开根节点
        $('#addRoleTab').tree('openFolder', $('#addRoleTab').find('.tree-branch')[1]);

        var grid_selector = '#grid-table';
        var $grid_selector = $(grid_selector);
        var pager_selector = '#grid-pager';
        var parent_column = $grid_selector.closest('[class*="col-"]');
        var colNames = ['主键ID', '登录ID', '姓名', '部门', '手机号码', '邮箱地址', '固定电话', '描述'];
        var width = pageContentArea.width() / colNames.length;
        var colModels = [
            {name: 'loginId', index: 'loginId', hidden: true},
            {name: 'loginCode', index: 'loginCode', hideWidth: 300, width: width},
            {name: 'name', index: 'name', hideWidth: 300, width: width},
            {name: 'deptName', index: 'deptName', hideWidth: 650, width: width},
            {name: 'loginPhone', index: 'loginPhone', hideWidth: 350, width: width},
            {name: 'emailAddr', index: 'emailAddr', hideWidth: 650, width: width},
            {name: 'localPhone', index: 'localPhone', hideWidth: 650, width: width},
            {name: 'comments', index: 'comments', hideWidth: 650, width: width}
        ];
        $grid_selector.jqGrid({
            url: ctx + '/tbSysLoginmsg/queryPageList',
            mtype: 'post',
            datatype: 'json',
            height: '100%',
            colNames: colNames,
            colModel: colModels,
            autowidth: true,
            altRows: true,
            rownumbers: true,
            viewrecords: true,
            multiselect: true,
            multiboxonly: true,
            rowNum: rowNum,
            rowList: rowList,
            pager: pager_selector,
            sortname: 'loginId',
            sortorder: 'asc',
            jsonReader: jsonReader,
            beforeRequest: function () {
                var postData = {};
                $('#queryPanel').find('[name^="search."]').each(function () {
                    var $this = $(this);
                    postData[$this.attr('name').replace(/search\./, '')] = $this.val();
                });
                // 获取部门树节点
                var selectedItems = $('#deptTreeview').tree('selectedItems');
                if (isNotEmpty(selectedItems)) {
                    postData['deptCode'] = selectedItems[0].additionalParameters.id;
                } else {
                    postData['deptCode'] = null;
                }
                $.extend($grid_selector.getGridParam('postData'), postData);
            },
            loadComplete: function () {
                setTimeout(function () {
                    $grid_selector.jqGrid('setGridWidth', parent_column.width());
                }, 20);
            },
            ondblClickRow: viewGridRow
        });

        //navButtons
        $grid_selector.jqGrid('navGrid', pager_selector, {
            add: false, edit: false, del: false, search: false, view: false, refresh: true,
            refreshicon: 'ace-icon fa fa-refresh green'
        }).navSeparatorAdd(pager_selector, {
            sepclass: 'ui-separator',
            sepcontent: ''
        }).navButtonAdd(pager_selector, {
            caption: '',
            title: '查看详细信息',
            buttonicon: 'ace-icon fa fa-search-plus info',
            onClickButton: viewGridRow,
            position: 'first'
        }).navButtonAdd(pager_selector, {
            caption: '',
            title: '导出Excel',
            buttonicon: 'ace-icon fa fa-file-excel-o green',
            onClickButton: expRowsToExcel,
            position: 'last'
        });

        // Form表单
        var theForm = $('#editTbSysLoginmsgForm');

        // 密码表单
        var pwdForm = $('#resetPwdForm');

        // 重置表单验证
        function resetPwdValidator() {
            var bootstrapValidator = pwdForm.data('bootstrapValidator');
            if (bootstrapValidator) {
                bootstrapValidator.destroy();
                pwdForm.data('bootstrapValidator', null);
                formValidator();
            }
        }

        $('#addBtn').click(function () {
            var selectedItems = $('#deptTreeview').tree('selectedItems');
            if (isNotEmpty(selectedItems)) {
                // 重置表单验证
                resetValidator();
                // 隐藏隐藏项
                $('.show').removeClass('show').addClass('hidden');
                // 显示保存按钮
                $('#saveTbSysLoginmsgBtn').removeClass('hidden');
                // 重置表单基本元素
                theForm.formReset();
                // 填充表单部门项
                $(':input[name="deptName"]').val(selectedItems[0].text);
                $(':input[name="deptName"]').attr('readonly', 'readonly');
                $(':input[name="deptCode"]').val(selectedItems[0].additionalParameters.id);
                // 启用loginCode验证
                $(':input[name="loginCode"]').removeAttr('readonly');
                theForm.bootstrapValidator('enableFieldValidators', 'loginCode', true);
                // 显示弹出层
                $.launchDialog('tbSysUserModal');
            } else {
                $(this).dynamicPop('请在左侧选择部门！');
            }
        });

        $('#editBtn').click(function () {
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                $(this).dynamicPop('请选择要编辑的记录!');
            } else if (rowIds.length > 1) {
                $(this).dynamicPop('不能选择多条记录编辑, 请选择一条记录!');
            } else {
                var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
                var loginId = $grid_selector.jqGrid('getRowData', rowId).loginId;
                // 重置表单验证
                resetValidator();
                $.ajax({
                    type: 'post',
                    async: true,// 异步请求
                    url: ctx + '/tbSysLoginmsg/querySingle',
                    dataType: 'json',
                    data: {
                        loginId: loginId
                    },
                    beforeSend: function () {
                        // 重置表单
                        theForm.formReset();
                        // 隐藏隐藏项
                        $('.show').removeClass('show').addClass('hidden');

                        $(':input[name="loginCode"]').attr('readonly', 'readonly');
                        $(':input[name="loginCode"]').val(loginId);
                        // 禁用loginCode验证
                        theForm.bootstrapValidator('enableFieldValidators', 'loginCode', false);
                        // 显示保存按钮
                        $('#saveTbSysLoginmsgBtn').removeClass('hidden');
                    },
                    success: function (data) {
                        // Form表单赋值
                        theForm.setForm(data);
                        // 显示Form表单
                        $.launchDialog('tbSysUserModal');
                    }
                });
            }
        });

        $('#delBtn').click(function () {
            // 获取选中的列表项
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds.length > 0) {
                $(this).confirm('确认要删除吗？', function () {
                    var ids = new Array();
                    $.each(rowIds, function (idx, rowId) {
                        var row = $grid_selector.jqGrid('getRowData', rowId);
                        ids.push(row.loginId);
                    });
                    $.ajax({
                        async: true,// 异步请求
                        type: 'post',
                        url: ctx + '/tbSysLoginmsg/delete',
                        dataType: 'json',
                        data: {
                            ids: ids.join(',')
                        },
                        success: function (data) {
                            if (data) {
                                // 删除成功将表格刷新
                                $grid_selector.trigger('reloadGrid', [{page: 1}]);
                            }
                        }
                    });
                });
            } else {
                $(this).dynamicPop('请从列表中选择一条记录删除!');
            }
        });

        $('#addRoleWizard').ace_wizard().on('finished.fu.wizard', function (e) {
            saveUserRoles();
        });

        // 重置向导
        function resetWizard() {
            var wizard = $('#addRoleWizard').data('fu.wizard');
            wizard.currentStep = 1;
            wizard.setState();
        }

        $('#addRoleBtn').click(function () {
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                $(this).dynamicPop('请选择要编辑的行!');
            } else if (rowIds.length > 1) {
                $(this).dynamicPop('不能编辑多行, 请选择一行!');
            } else {
                var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
                var loginCode = $grid_selector.jqGrid('getRowData', rowId).loginCode;
                // 重置div
                $('#roleTreeTab').tree('destroy');
                $('#roleTreeDiv').html('<ul id="roleTreeTab"></ul>');
                // 初始化树
                $('#roleTreeTab').ace_tree({
                    dataSource: remoteRoleDateSource,
                    loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
                    'open-icon': 'ace-icon fa fa-chevron-down',
                    'close-icon': 'ace-icon fa fa-chevron-right',
                    'itemSelect': true,
                    'folderSelect': true,
                    'multiSelect': true,
                    'selected-icon': null,
                    'unselected-icon': null,
                    'folder-open-icon': 'ace-icon tree-plus',
                    'folder-close-icon': 'ace-icon tree-minus',
                    'cacheItems': false
                });
                // 默认展开根节点
                $('#roleTreeTab').tree('openFolder', $('#roleTreeTab').find('.tree-branch')[1]);
                // 查询已配置角色
                $.ajax({
                    async: false,
                    type: 'post',
                    url: ctx + '/tbSysUserRole/queryList',
                    dataType: 'json',
                    data: {
                        loginCode: loginCode
                    },
                    success: function (data) {
                        $('#roleTreeTab').tree('discloseAll');
                        for (var i = 0; i < data.length; i++) {
                            var idStr = '#' + data[i].roleCode;
                            $('#roleTreeTab').tree('selectItem', $('#roleTreeTab ' + idStr));
                        }
                    }
                });
                // 显示模态框
                $.launchDialog('addRoleModal');
            }
        });

        $('#saveRoleBtn').click(function () {
            var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
            var loginCode = $grid_selector.jqGrid('getRowData', rowId).loginId;

            var roleItems = $('#roleTreeTab').tree('selectedItems');
            var roleCodeArr = new Array();
            for (var i = 0; i < roleItems.length; i++) {
                roleCodeArr[i] = roleItems[i].additionalParameters.id;
            }
            $.ajax({
                type: 'post',
                async: true,// 异步请求
                url: ctx + '/tbSysUserRole/save',
                dataType: 'json',
                data: {
                    loginCode: loginCode,
                    roleCode: roleCodeArr.join(',')
                },
                success: function (data) {
                    if (data) {
                        $('#roleTreeTab').tree('destroy');
                        $('#roleTreeDiv').html('<ul id="roleTreeTab"></ul>');
                        // 关闭窗口
                        $('#addRoleModal').modal('hide');
                        // 删除成功将表格刷新
                        reloadJqGrid('json');
                    }
                }
            });
        });


        function saveUserRoles() {
            var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
            var loginCode = $grid_selector.jqGrid('getRowData', rowId).loginCode;

            var functionRoleSelect = $('#addFunctionRoleTab').tree('selectedItems');
            var functionRoles = new Array();
            for (var i = 0; i < functionRoleSelect.length; i++) {
                functionRoles[i] = functionRoleSelect[i].additionalParameters.id;
            }

            var dataRoleSelect = $('#addDataRoleTab').tree('selectedItems');
            var dataRoles = new Array();
            for (var i = 0; i < dataRoleSelect.length; i++) {
                dataRoles[i] = dataRoleSelect[i].additionalParameters.id;
            }

            $.ajax({
                async: true,// 异步请求
                type: 'post',
                dataType: 'json',
                url: ctx + '/tbSysLoginmsg/saveUserRoles',
                data: {
                    loginCode: loginCode,
                    functionRoles: functionRoles.join(','),
                    dataRoles: dataRoles.join(',')
                },
                success: function (data) {
                    if (data.success == true) {
                        $grid_selector.trigger('reloadGrid', [{page: 1}]);
                        // 关闭窗口
                        $('#addRoleModal').modal('hide');
                        $.successMessage(data.msg, pageContentArea);
                    } else {
                        $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', theForm);
                    }
                },
                error: function () {
                    $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', theForm);
                }
            });
        }

        $('#resetPwdBtn').click(function () {
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                $(this).dynamicPop('请选择要编辑的记录!');
            } else if (rowIds.length > 1) {
                $(this).dynamicPop('不能选择多条记录编辑, 请选择一条记录!');
            } else {
                var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
                var loginId = $grid_selector.jqGrid('getRowData', rowId).loginId;
                // 重置表单验证
                resetPwdValidator();
                // 隐藏原密码输入框
                $('#pwdModalLabel span').text('重置密码');
                $(':input[name="prePassword"]').closest('[class*="form-group"]').removeClass('show').addClass('hidden');
                // 填充表单部门项
                $(':input').val(null);
                $(':input[name="loginId"]').val(loginId);
                // 显示弹出框
                $.launchDialog('resetPwdModal');
            }
        });

        function viewGridRow() {
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                $(this).dynamicPop('请选择要查看的记录!');
            } else if (rowIds.length > 1) {
                $(this).dynamicPop('不能选择多条记录查看, 请选择一条记录!');
            } else {
                var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
                var loginId = $grid_selector.jqGrid('getRowData', rowId).loginId;
                // 重置表单验证
                resetValidator();
                $.ajax({
                    type: 'post',
                    async: true,// 异步请求
                    url: ctx + '/tbSysLoginmsg/querySingle',
                    dataType: 'json',
                    data: {
                        loginId: loginId
                    },
                    beforeSend: function () {
                        // 重置表单
                        theForm.formReset();
                        // 显示隐藏项
                        theForm.find('.hidden').removeClass('hidden').addClass('show');
                        // 隐藏保存按钮
                        $('#saveTbSysLoginmsgBtn').addClass('hidden');
                        $(':input[name="loginCode"]').removeAttr('readonly');
                        $(':input[name="deptName"]').removeAttr('readonly');
                    },
                    success: function (data) {
                        // Form表单赋值
                        theForm.setForm(data);
                        // 显示Form表单
                        $.launchDialog('tbSysUserModal');
                    }
                });
            }
        }

        // 导出excel
        function expRowsToExcel() {
            var colFieldNames = new Array();
            $.each(colModels, function (idx, obj) {
                colFieldNames.push(obj.index);
            });
            var sortName = $grid_selector.jqGrid('getGridParam', 'sortname');// 排序列
            var sortOrder = $grid_selector.jqGrid('getGridParam', 'sortorder');// 排序方式：desc、asc
            var postData = {};
            $('#queryPanel').find('[name^="search."]').each(function () {
                var $this = $(this);
                postData[$this.attr('name').replace(/search\./, '')] = $this.val();
            });
            postData.titles = colNames;
            postData.fields = colFieldNames;
            postData.sidx = sortName;
            postData.sord = sortOrder;
            $.ajax({
                type: 'post',
                async: true,// 异步请求
                url: ctx + '/tbSysLoginmsg/expExcel',
                dataType: 'json',
                data: postData,
                success: function (data) {
                    downloadFile(data.result);// 下载文件
                }
            });
        }

        // 表单验证
        function formValidator() {
            theForm.bootstrapValidator({
                group: '.rowGroup',
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    loginCode: {
                        message: '登录ID验证失败',
                        validators: {
                            notEmpty: {
                                message: '登录ID不能为空'
                            },
                            stringLength: {
                                min: 6,
                                max: 20,
                                message: '登录ID长度必须在6到20位之间'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z0-9_]+$/,
                                message: '登录ID只能包含大、小写字母，数字和下划线'
                            },
                            threshold: 6, //有6字符以上才发送ajax请求
                            remote: {//ajax验证, result:{"valid",true or false}, 表示正确: {"valid",true}
                                url: ctx + '/tbSysLoginmsg/checkInputField',
                                message: '登录ID已存在',
                                delay: 1000,//设置2秒发送一次ajax（默认输入一个字符，提交一次）
                                type: 'POST',//请求方式
                                //自定义提交数据, 默认值提交当前input value
                                data: function (validator) {
                                    return {
                                        loginId: $('[name="loginId"]').val()
                                    };
                                }
                            }
                        }
                    },
                    name: {
                        message: '姓名验证失败',
                        validators: {
                            notEmpty: {
                                message: '姓名不能为空'
                            },
                            stringLength: {
                                min: 0,
                                max: 10,
                                message: '姓名长度不能大于10位'
                            }
                        }
                    },
                    loginPhone: {
                        validators: {
                            notEmpty: {
                                message: '手机号码不能为空'
                            },
                            Phone: {
                                country: 'CN',
                                message: '请输入正确的手机号码'
                            }
                        }
                    },
                    emailAddr: {
                        validators: {
                            notEmpty: {
                                message: '邮箱地址不能为空'
                            },
                            emailAddress: {
                                message: '邮箱地址格式有误'
                            }
                        }
                    }

                    /*                 prePassword: {
                                         message: '密码验证失败',
                                         validators: {
                                             notEmpty: {
                                                 message: '密码不能为空'
                                             },
                                             stringLength: {
                                                 min: 6,
                                                 max: 20,
                                                 message: '密码长度必须在6到20位之间'
                                             },
                                             regexp: {
                                                 regexp: /^[a-zA-Z0-9_@\.#\$&]+$/,
                                                 message: '密码只能包含大、小写字母，数字，下划线和_@.#$&'
                                             },
                                             threshold: 6, //有6字符以上才发送ajax请求
                                             remote: {//ajax验证, result:{"valid",true or false}, 表示正确: {"valid",true}
                                                 url: ctx + '/tbSysLoginmsg/checkInputField',
                                                 message: '你输入的密码错误',
                                                 delay: 1000,//设置2秒发送一次ajax（默认输入一个字符，提交一次）
                                                 type: 'POST',//请求方式
                                                 //自定义提交数据, 默认值提交当前input value
                                                 data: function (validator) {
                                                     return {
                                                         loginId: $(':input[name="loginId"]').val(),
                                                         loginPasswd: $(':input[name="prePassword"]').val()
                                                     };
                                                 }
                                             }
                                         }
                                     },
                                     loginPasswd: {
                                         message: '密码验证失败',
                                         validators: {
                                             notEmpty: {
                                                 message: '密码不能为空'
                                             },
                                             stringLength: {
                                                 min: 6,
                                                 max: 20,
                                                 message: '密码长度必须在6到20位之间'
                                             },
                                             identical: {
                                                 field: 'rePassword',
                                                 message: '两次输入的密码不一致'
                                             },
                                             regexp: {
                                                 regexp: /^[a-zA-Z0-9_@\.#\$&]+$/,
                                                 message: '密码只能包含大、小写字母，数字，下划线和_@.#$&'
                                             }
                                         }
                                     },
                                     rePassword: {
                                         message: '密码验证失败',
                                         validators: {
                                             notEmpty: {
                                                 message: '密码不能为空'
                                             },
                                             stringLength: {
                                                 min: 6,
                                                 max: 20,
                                                 message: '密码长度必须在6到20位之间'
                                             },
                                             identical: {
                                                 field: 'loginPasswd',
                                                 message: '两次输入的密码不一致'
                                             },
                                             regexp: {
                                                 regexp: /^[a-zA-Z0-9_@\.#\$&]+$/,
                                                 message: '密码只能包含大、小写字母，数字，下划线和_@.#$&'
                                             }
                                         }
                                     }*/
                }
            });

            pwdForm.bootstrapValidator({
                group: '.rowGroup',
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    loginPasswd: {
                        message: '密码验证失败',
                        validators: {
                            notEmpty: {
                                message: '密码不能为空'
                            },
                            stringLength: {
                                min: 6,
                                max: 20,
                                message: '密码长度必须在6到20位之间'
                            },
                            identical: {
                                field: 'rePassword',
                                message: '两次输入的密码不一致'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z0-9_@\.#\$&]+$/,
                                message: '密码只能包含大、小写字母，数字，下划线和_@.#$&'
                            }
                        }
                    },
                    rePassword: {
                        message: '密码验证失败',
                        validators: {
                            notEmpty: {
                                message: '密码不能为空'
                            },
                            stringLength: {
                                min: 6,
                                max: 20,
                                message: '密码长度必须在6到20位之间'
                            },
                            identical: {
                                field: 'loginPasswd',
                                message: '两次输入的密码不一致'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z0-9_@\.#\$&]+$/,
                                message: '密码只能包含大、小写字母，数字，下划线和_@.#$&'
                            }
                        }
                    },

                    prePassword: {
                        message: '密码验证失败',
                        validators: {
                            notEmpty: {
                                message: '密码不能为空'
                            },
                            stringLength: {
                                min: 6,
                                max: 20,
                                message: '密码长度必须在6到20位之间'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z0-9_@\.#\$&]+$/,
                                message: '密码只能包含大、小写字母，数字，下划线和_@.#$&'
                            },
                            threshold: 6, //有6字符以上才发送ajax请求
                            remote: {//ajax验证, result:{"valid",true or false}, 表示正确: {"valid",true}
                                url: ctx + '/tbSysLoginmsg/checkInputField',
                                message: '你输入的密码错误',
                                delay: 1000,//设置2秒发送一次ajax（默认输入一个字符，提交一次）
                                type: 'POST',//请求方式
                                //自定义提交数据, 默认值提交当前input value
                                data: function (validator) {
                                    return {
                                        loginId: $(':input[name="loginId"]').val(),
                                        loginPasswd: $(':input[name="prePassword"]').val()
                                    };
                                }
                            }
                        }
                    }
                }
            });
        }


        // 保存重置密码表单
        $('#savePwdBtn').click(function () {
            //开启验证
            pwdForm.data('bootstrapValidator').validate();

            if (pwdForm.data('bootstrapValidator').isValid()) {
                $.ajax({
                    async: true,// 异步请求
                    type: 'post',
                    dataType: 'json',
                    url: ctx + '/tbSysLoginmsg/resetPassword',
                    data: {
                        loginId: pwdForm.serializeObject().loginId,
                        loginPasswd: pwdForm.serializeObject().loginPasswd,
                        rePassword: pwdForm.serializeObject().rePassword
                    },
                    success: function (data) {
                        if (data.success == true) {
                            $grid_selector.trigger('reloadGrid', [{page: 1}]);
                            // 关闭窗口
                            $('#resetPwdModal').modal('hide');
                            $.successMessage(data.msg, pageContentArea);
                        } else {
                            $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', pwdForm);
                        }
                    },
                    error: function () {
                        $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', pwdForm);
                    }
                });
            }
        });


        // 初始化表单验证
        formValidator();

        // 保存表单
        $('#saveTbSysLoginmsgBtn').click(function () {
            //开启验证
            theForm.data('bootstrapValidator').validate();
            if (theForm.data('bootstrapValidator').isValid()) {
                $.ajax({
                    async: true,// 异步请求
                    type: 'post',
                    dataType: 'json',
                    url: ctx + '/tbSysLoginmsg/save',
                    data: JSON.stringify(theForm.serializeObject()),
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        if (data.success == true) {
                            $grid_selector.trigger('reloadGrid', [{page: 1}]);
                            // 关闭窗口
                            $('#tbSysUserModal').modal('hide');
                            $.successMessage(data.msg, pageContentArea);
                        } else {
                            $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', theForm);
                        }
                    },
                    error: function () {
                        $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', theForm);
                    }
                });
            }
        });


        //重置表单验证
        function resetValidator() {
            var bootstrapValidator = theForm.data('bootstrapValidator');
            if (bootstrapValidator) {
                bootstrapValidator.destroy();
                theForm.data('bootstrapValidator', null);
                formValidator();
            }
        }

        // 显示隐藏查询条件
        $('#searBtn').click(function () {
            $(this).find('i').toggleClass('fa-arrow-down');
            $(this).find('i').toggleClass('fa-arrow-up');
        });

        $('#searchBtn').click(function () {
            $grid_selector.trigger('reloadGrid', [{page: 1}]);
        });

        // 重置查询表单
        $('#resetBtn').click(function () {
            $('#queryPanel').find(':input(:text)').each(function () {
                $(this).val('');
            });
            $('#queryPanel').find('input[type=checkbox],input[type=radio]').each(function () {
                $(this).removeAttr('checked');
            });
            reloadJqGrid('json');
        });

        // 初始化日期控件
        $('.date-picker').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            todayHighlight: true,
            clearBtn: true,//清除按钮
            format: 'yyyy-mm-dd'//日期格式
        }).next().on(ace.click_event, function () {
            $(this).prev().focus();
        });

        $('.input-daterange').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            //todayHighlight: true,
            clearBtn: true,//清除按钮
            format: 'yyyy-mm-dd'//日期格式
        });


        $('#deptTreeDiv').ace_tree({
            dataSource: remoteDeptDateSource,
            loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
            'open-icon': 'ace-icon fa fa-chevron-down',
            'close-icon': 'ace-icon fa fa-chevron-right',
            'itemSelect': true,
            'folderSelect': true,
            'multiSelect': false,
            'selected-icon': null,
            'unselected-icon': null,
            'folder-open-icon': 'ace-icon tree-plus',
            'folder-close-icon': 'ace-icon tree-minus'
        });

        $('#deptSingleSelectedBtn').click(function () {
                var selectedItems = $('#deptTreeDiv').tree('selectedItems');
                if (isNotEmpty(selectedItems)) {
                    if ($('#deptSingleSelectorModal').attr('search') == 'search') {
                        $(':text[name="search.deptCode"]').val(selectedItems[0].additionalParameters.id);
                        $(':text[name="search.deptName"]').val(selectedItems[0].text);
                        $('#deptSingleSelectorModal').removeAttr('type');
                    } else {
                        $(':text[name="deptCode"]').val(selectedItems[0].additionalParameters.id);
                        $(':text[name="deptName"]').val(selectedItems[0].text);
                    }
                    $('#deptSingleSelectorModal').modal('hide');
                } else {
                    $(this).dynamicPop('请选择部门!');
                }
            }
        );

        function reloadJqGrid(datatype) {
            $grid_selector.jqGrid('setGridParam', {datatype: datatype}).trigger('reloadGrid', [{page: 1}]);
        }

        //resize to fit page size
        $(window).on('resize.jqGrid', function () {
            $grid_selector.jqGrid('setGridWidth', parent_column.width());
        });

        $(document).one('ajaxloadstart.page', function (e) {
            $.jgrid.gridDestroy(grid_selector);
            $('.ui-jqdialog').remove();
        });

        // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
        $(document).on('show.bs.modal', '.modal', function () {
            var zIndex = 1040 + (10 * $('.modal:visible').length);
            $(this).css('z-index', zIndex);
            setTimeout(function () {
                $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
            }, 0);
        });

    });

});
